import {ref, computed, reactive} from 'vue'
import { defineStore } from 'pinia'
import * as userAPI from '@/api/user'
import * as auth from '@/utils/auth'


export const useUserStore = defineStore('user', () => {
  const user = reactive<{
    username?: string,
    permissionInformation: Permission[]
  }>({
    username: undefined,
    permissionInformation: []
  })

  function isEmpty() {
    return typeof(user.username) === 'undefined'
  }


  const login = async (formData: {username: string, password: string}) => {
    const data = await userAPI.login({
      accountUsername: formData.username,
      accountPassword: formData.password
    })

    if (data) {
      // 有值，则证明成功拿到数据
      user.username = data.username
      user.permissionInformation = data.permissionInformation
      auth.setToken(data.token)
    }
  }

  const logout = async () => {
    user.username = undefined
    user.permissionInformation = []
    auth.removeToken()
  }

  return { user, isEmpty, login, logout}
},{
  persist: {
    enabled: true
  }
})
